
#import "NSDate+XMExtension.h"

@implementation NSDate (XMExtension)

static NSArray *weekArr_;
static NSDateFormatter *fmt_;
static NSCalendar *calendar_;

+ (void)load {
    
    weekArr_ = @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"];
    //读取内存时调用一次
    fmt_ = [[NSDateFormatter alloc] init];
    if ([NSCalendar instancesRespondToSelector:@selector(calendarWithIdentifier:)]) {
        calendar_ = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    } else {
        calendar_ = [NSCalendar currentCalendar];
    }
}

//第一次使用这个类 只调用一次
//+ (void)initialize {
//    
//    fmt_ = [[NSDateFormatter alloc] init];
//    if (iOS(8.0)) {
//        calendar_ = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
//    } else {
//        calendar_ = [NSCalendar currentCalendar];
//    }
//}

- (BOOL)xm_isThisYear {
    
    fmt_.dateFormat = @"yyyy";
    
    NSString *selfYear = [fmt_ stringFromDate:self];
    NSString *nowYear = [fmt_ stringFromDate:[NSDate date]];
    
    return [selfYear isEqualToString:nowYear];
}

- (BOOL)xm_isToday {
    
    fmt_.dateFormat = @"yyyyMMdd";
    
    NSString *selfDay = [fmt_ stringFromDate:self];
    NSString *nowDay = [fmt_ stringFromDate:[NSDate date]];
    
    return [selfDay isEqualToString:nowDay];
}

- (BOOL)xm_isYesterday
{
    // 判断self这个日期是否为昨天
    
    // self == 2015-10-31 23:07:08 -> 2015-10-31 00:00:00
    // now  == 2015-11-01 14:39:20 -> 2015-11-01 00:00:00
    
    fmt_.dateFormat = @"yyyyMMdd";
    
    NSString *selfString = [fmt_ stringFromDate:self]; // 20151031
    NSString *nowString = [fmt_ stringFromDate:[NSDate date]]; // 20151101
    
    NSDate *selfDate = [fmt_ dateFromString:selfString]; // 2015-10-31 00:00:00
    NSDate *nowDate = [fmt_ dateFromString:nowString]; // 2015-11-01 00:00:00
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *cmps = [calendar_ components:unit fromDate:selfDate toDate:nowDate options:0];
    
    return cmps.year == 0
    && cmps.month == 0
    && cmps.day == 1;
}

- (BOOL)xm_isThisWeek {
    // 判断self是否是本周
    fmt_.dateFormat = @"yyyyMMdd";
    
    NSString *selfString = [fmt_ stringFromDate:self]; // 20151031
    NSString *nowString = [fmt_ stringFromDate:[NSDate date]]; // 20151101
    
    NSDate *selfDate = [fmt_ dateFromString:selfString]; // 2015-10-31 00:00:00
    NSDate *nowDate = [fmt_ dateFromString:nowString]; // 2015-11-01 00:00:00
    //kCFCalendarUnitWeekOfYear：今年第几周
    NSDateComponents *selfCps = [calendar_ components:NSCalendarUnitWeekOfYear fromDate:selfDate];
    NSDateComponents *nowCps = [calendar_ components:NSCalendarUnitWeekOfYear fromDate:nowDate];
    
    if (selfCps.weekOfYear == nowCps.weekOfYear) {
        return YES;
    } else {
        return NO;
    }
}

- (BOOL)xm_isQianTian
{
    // 判断self这个日期是否为昨天
    
    // self == 2015-10-31 23:07:08 -> 2015-10-31 00:00:00
    // now  == 2015-11-01 14:39:20 -> 2015-11-01 00:00:00
    
    fmt_.dateFormat = @"yyyyMMdd";
    
    NSString *selfString = [fmt_ stringFromDate:self]; // 20151031
    NSString *nowString = [fmt_ stringFromDate:[NSDate date]]; // 20151101
    
    NSDate *selfDate = [fmt_ dateFromString:selfString]; // 2015-10-31 00:00:00
    NSDate *nowDate = [fmt_ dateFromString:nowString]; // 2015-11-01 00:00:00
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *cmps = [calendar_ components:unit fromDate:selfDate toDate:nowDate options:0];
    
    return cmps.year == 0
    && cmps.month == 0
    && cmps.day == 2;
}

- (BOOL)xm_isTomorrow
{
    fmt_.dateFormat = @"yyyyMMdd";
    
    NSString *selfString = [fmt_ stringFromDate:self]; // 20151031
    NSString *nowString = [fmt_ stringFromDate:[NSDate date]]; // 20151101
    
    NSDate *selfDate = [fmt_ dateFromString:selfString]; // 2015-10-31 00:00:00
    NSDate *nowDate = [fmt_ dateFromString:nowString]; // 2015-11-01 00:00:00
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *cmps = [calendar_ components:unit fromDate:selfDate toDate:nowDate options:0];
    
    return cmps.year == 0
    && cmps.month == 0
    && cmps.day == -1;
}

+ (NSDate *)getTomorrowDate {
    
    fmt_.dateFormat = @"yyyyMMdd";
    NSString *nowString = [fmt_ stringFromDate:[NSDate date]];
    NSDate *nowDate = [fmt_ dateFromString:nowString];
    
    return [nowDate dateByAddingTimeInterval:24 * 60 * 60];
}

+ (NSDate *)getAWeekLaterDate {
    
    fmt_.dateFormat = @"yyyyMMdd";
    NSString *nowString = [fmt_ stringFromDate:[NSDate date]];
    NSDate *nowDate = [fmt_ dateFromString:nowString];
    
    return [nowDate dateByAddingTimeInterval:24 * 60 * 60 * 7];
}

+ (NSDate *)getAfterSomeDayDateWithDayCount:(NSInteger)count {
    
    fmt_.dateFormat = @"yyyyMMdd";
    NSString *nowString = [fmt_ stringFromDate:[NSDate date]];
    NSDate *nowDate = [fmt_ dateFromString:nowString];
    
    return [nowDate dateByAddingTimeInterval:24 * 60 * 60 * count];
}

+ (NSString *)timeAgoWithDateStr:(NSString *)dateStr {

    // 获得发帖日期
    fmt_.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *createdAtDate = [fmt_ dateFromString:dateStr];
    
//    if (createdAtDate.xm_isThisYear) { // 今年
        if (createdAtDate.xm_isToday) { // 今天
            // 手机当前时间
            NSDate *nowDate = [NSDate date];
            NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
            NSDateComponents *cmps = [calendar_ components:unit fromDate:createdAtDate toDate:nowDate options:0];
            
            if (cmps.hour >= 1) { // 时间间隔 >= 1小时
                return [NSString stringWithFormat:@"%zd小时前", cmps.hour];
            } else if (cmps.minute >= 1) { // 1小时 > 时间间隔 >= 1分钟
                return [NSString stringWithFormat:@"%zd分钟前", cmps.minute];
            } else { // 1分钟 > 分钟
                return @"刚刚";
            }
        } else if (createdAtDate.xm_isYesterday) { // 昨天
//            fmt_.dateFormat = @"昨天 HH:mm:ss";
//            fmt_.dateFormat = @"昨天HH:mm";
            return @"一天前";
        } else if (createdAtDate.xm_isQianTian) {
            return @"两天前";
        } else { // 其他
//            fmt_.dateFormat = @"MM-dd HH:mm:ss";
//            fmt_.dateFormat = @"MM-dd HH:mm";
            return @"三天前";
        }
//    } else { // 非今年
//        return dateStr;
//    }
}

//获取剩余支付时间 10分钟封顶
+ (NSString *)remainingTime:(NSString *)acceptTime {
    //yyyy-MM-dd HH:mm:ss
    fmt_.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *acceptTimeDate = [fmt_ dateFromString:acceptTime];
    NSDate *afterTenMinDate = [acceptTimeDate dateByAddingTimeInterval:10 * 60];
    NSDate *nowDate = [NSDate date];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps = [calendar_ components:unit fromDate:nowDate toDate:afterTenMinDate options:0];
    if ([afterTenMinDate timeIntervalSinceDate:nowDate] < 0) {
        return @"支付超时，请重新赴约";
    }
    return [NSString stringWithFormat:@"%02zd:%02zd", cmps.minute, cmps.second];
}

//我接她倒计时
+ (NSTimeInterval)meetRemainingTime:(NSDate *)acceptTimeDate cd:(double)second {
    
    NSDate *afterTenMinDate = [acceptTimeDate dateByAddingTimeInterval:second];
    return [afterTenMinDate timeIntervalSinceDate:[NSDate date]];
}

//获取验证码倒计时
+ (NSInteger)identifyingCodeRemainingTime:(NSDate *)obtainTime {
    NSDate *afterOneMinDate = [obtainTime dateByAddingTimeInterval:60];
    NSDate *nowDate = [NSDate date];
    NSTimeInterval s = [afterOneMinDate timeIntervalSinceDate:nowDate];
    return s < 0 ? 0 : s;
}

+ (void)asyncGetInternetDate:(void(^)(NSDate *))block {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 2;
    [manager GET:@"http://m.baidu.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
        date = [date substringFromIndex:5];
        date = [date substringToIndex:[date length] - 4];
        NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
        dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
        NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60 * 60 * 8];
        block(netDate);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        block([NSDate date]);
    }];
}

+ (NSString *)chatTimeAgoWithTimestamp:(double)timeIntervalInMilliSecond {
    if (timeIntervalInMilliSecond == 0) {
        return @"";
    }
    NSDate *messageDate = [self dateWithTimeIntervalInMilliSecSince1970:timeIntervalInMilliSecond];
    if (messageDate.xm_isThisYear) { // 今年
        if (messageDate.xm_isToday) { // 今天
            NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
            NSDateComponents *cmps = [calendar_ components:unit fromDate:messageDate];
            if (cmps.hour > 11) {
                //下午
                return [NSString stringWithFormat:@"下午%zd:%02zd", cmps.hour - 12 == 0 ? 12 : cmps.hour - 12, cmps.minute];
            } else {
                //上午
                return [NSString stringWithFormat:@"上午%zd:%02zd", cmps.hour, cmps.minute];
            }
        } else if (messageDate.xm_isYesterday) { // 昨天
            return @"昨天";
        } else if (messageDate.xm_isThisWeek) {
            NSDateComponents *cps = [calendar_ components:NSCalendarUnitWeekday fromDate:messageDate];
            return [NSString stringWithFormat:@"星期%@", weekArr_[cps.weekday - 1]];
        } else { // 其他
            fmt_.dateFormat = @"MM-dd";
            return [fmt_ stringFromDate:messageDate];
        }
    } else { // 非今年
        fmt_.dateFormat = @"yyyy/MM/dd";
        return [fmt_ stringFromDate:messageDate];
    }
}

#pragma mark - 私有方法
+ (NSDate *)dateWithTimeIntervalInMilliSecSince1970:(double)timeIntervalInMilliSecond {
    NSDate *ret = nil;
    double timeInterval = timeIntervalInMilliSecond;
    // judge if the argument is in secconds(for former data structure).
    if(timeIntervalInMilliSecond > 140000000000) {//1477711569462  1477725996
        timeInterval = timeIntervalInMilliSecond / 1000;
    }
    ret = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    
    return ret;
}

@end
